package com.usefullc.proxy.test.http.test;

import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpObject;

import java.nio.ByteBuffer;

/**
 * @author: Sampson
 * @date: 2022-08-01 15:49
 */
public class HttpProxyReplyHandler extends SimpleChannelInboundHandler<HttpObject> {

    private Channel remoteChannel;

    public HttpProxyReplyHandler(Channel remoteChannel) {
        super(false);
        this.remoteChannel = remoteChannel;

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        System.err.println("流量来源：" + ctx + ",流量去向：" + remoteChannel);

        if (msg instanceof DefaultHttpResponse) {
            DefaultHttpResponse defaultHttpResponse = (DefaultHttpResponse) msg;
            System.out.println(msg);

        } else if (msg instanceof DefaultHttpContent) {
            System.err.println("DefaultHttpContent");
            DefaultHttpContent defaultHttpContent = (DefaultHttpContent) msg;
            ByteBuf byteBuf = defaultHttpContent.content();
            ByteBuffer copyByteBuf = ByteBuffer.allocate(byteBuf.writerIndex());
            byteBuf.getBytes(0, copyByteBuf);
            char[] chars = HexUtil.encodeHex(copyByteBuf.array());
            System.out.println("十六进制，" + ctx);
            for (int i = 0; i < chars.length; i += 2) {
                System.out.print(chars[i] + "" + chars[i + 1] + " ");
            }
            System.out.println();

//            System.out.println(msg);
        } else {
            System.err.println("not defaultHttpResponse");
            System.out.println(msg);
        }
//        ByteBuffer copyByteBuf = ByteBuffer.allocate(byteBuf.writerIndex());
//        byteBuf.getBytes(0,copyByteBuf);
//        char[] chars = HexUtil.encodeHex(copyByteBuf.array());
//        System.out.println("十六进制，"+ctx);
//        for (int i = 0; i < chars.length; i+=2) {
//            System.out.print(chars[i]+""+chars[i+1]+" ");
//        }
//        System.out.println();
//        remoteChannel.writeAndFlush(msg);
        remoteChannel.writeAndFlush(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        flushAndClose(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        /**
         * 连接断开时关闭另一端连接。
         * 如果代理到远端服务器连接断了也同时关闭代理到客户的连接。
         * 如果代理到客户端的连接断了也同时关闭代理到远端服务器的连接。
         */
        flushAndClose(remoteChannel);
    }

    private void flushAndClose(Channel ch) {
        if (ch != null && ch.isActive()) {
            ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }

}
